<?php
class Pages{
	/**
	 * получаем список страниц для меню
	 */
	public static function getMenu(){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT `pages`.`menu_name`, 
					 `pages`.`url`,
					 `pages`.`ID_page`
		FROM `pages`
		WHERE `pages`.`hidden` = 0
		ORDER BY `pages`.`sort_num`";
		return $objDB->select($stmt);
	}
	
	/**
	 * получаем страницу по его url
	 *
	 */
	public static function getPageByUrl($url){
    $objDB = Service_Database::instance();
		$stmt = "
		SELECT *
		FROM `pages` 
		WHERE `pages`.`url` = '" . $url . "'";
		return $objDB->selectOne($stmt);
	}
	
	/**
	 * получаем страницу по его ID
	 *
	 */
	public static function getPageByID($idPage){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT *
		FROM `pages`
		WHERE `pages`.`ID_page` = '" . $idPage . "'";
		return $objDB->selectOne($stmt);
	}
	
	/**
	 * обновляем страницу
	 */
	public static function updatePage($arrPage){
		$objDB = Service_Database::instance();
		$stmt = "
		UPDATE `pages`
		SET `pages`.`title` = '" . $arrPage['title'] . "',
				`pages`.`text` = '" . $arrPage['text'] . "',
				`pages`.`url` = '" . $arrPage['url'] . "',
				`pages`.`menu_name` = '" . $arrPage['menu_name'] . "'
		WHERE `pages`.`ID_page` = " . $arrPage['ID_page'];
		return $objDB->query($stmt);
	}
	
	/**
	 * добавляем страницу
	 *
	 */
	public static function addPage($arrPage){
		$objDB = Service_Database::instance();
		$stmt = "
		INSERT INTO `pages` (`title`,`text`,`url`, `menu_name`)
		VALUES ('" . $arrPage['title'] . "', '" . $arrPage['text'] . "', '" . $arrPage['url'] . "',  '" . $arrPage['menu_name'] . "')";
		return $objDB->query($stmt);
	}
	
	/**
	 * обновляем sortNum
	 */
	public static function updateSortNum($order){
		$objDB = Service_Database::instance();
		$num = 0;
		$stmtWhen = '';
		foreach ($order as $order){
			$id = substr($order, 5);
			$stmtWhen .= ' WHEN ' . $id . ' then ' . $num . ' ';
			$arrIds[] = $id;
			$num++;
		}
		$stmt = '
		UPDATE `pages` 
		SET `sort_num` = CASE `ID_page`  ' . $stmtWhen . ' END 
		WHERE `ID_page` in(' . join(', ', $arrIds) . ')';
		return $objDB->query($stmt);
	}
	
	/**
	 * удалить страницу
	 */
	public static function deletePage($idPage){
		$objDB = Service_Database::instance();
		$stmt = "
		DELETE FROM `pages`
		WHERE `pages`.`ID_page` = " . $idPage;
		return $objDB->query($stmt);
	}
	
	/**
	 * проверка существования url
	 *
	 */
	public static function checkUrl($url, $idPage){
		$objDB = Service_Database::instance();
		$stmt = "
		SELECT COUNT(`pages`.`ID_page`)
		FROM `pages`
		WHERE `pages`.`url` = '" . $url . "' AND `pages`.`ID_page` !=" . $idPage;
		return $objDB->selectSimpleField($stmt);
	}
}
?>